import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { successResponse } from '@/lib/response';

async function handler(req: NextRequest) {
  const { page = 1, pageSize = 10, categoryId, title, menuId } = await req.json();

  const where: any = {};

  // 同时支持 categoryId 与 menuId 的筛选，不互相覆盖
  const relationFilter: any = {};
  if (categoryId) {
    relationFilter.categoryId = categoryId;
  }
  if (menuId) {
    relationFilter.category = { menuId };
  }
  if (Object.keys(relationFilter).length) {
    where.categories = { some: relationFilter };
  }

  if (title) {
    where.title = {
      contains: title,
      mode: 'insensitive',
    };
  }

  const [records, total] = await Promise.all([
    prisma.content.findMany({
      where,
      take: pageSize,
      skip: (page - 1) * pageSize,
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        categories: {
          include: {
            category: true,
          },
        },
        cover: true,
      },
    }),
    prisma.content.count({ where }),
  ]);

  return successResponse({
    records: records.map(item => ({
      ...item,
      categories: item.categories.map(c => c.category),
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString(),
    })),
    total,
    page,
    pageSize,
  });
}

export const POST = withMiddleware(handler);